﻿using Company.Application.Hardware.Models;
using Company.Application.Share.Config;
using Company.Core.Attributes;
using Company.Hardware.Camera;
using Company.Hardware.Detector;
using Company.Logger;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Navigation;

namespace Company.Application.Hardware.Services
{
    /// <summary>
    /// 硬件生命周期管理类
    /// </summary>
    [ExposedService(Lifetime = Lifetime.Singleton, AutoInitialize = true)]
    public class HardwareLifetimeManager
    {
        private readonly ISettingProvider _settingProvider;
        public HardwareLifetimeManager(ISettingProvider settingProvider
            , ICamera camera
            , IDetector detector
            )
        {
            _settingProvider = settingProvider;
            Camera = camera;
            Detector = detector;
        }
        public bool Initialized { get; set; }
        public ICamera Camera { get; }
        public IDetector Detector { get; }

        /// <summary>
        /// 初始化所有硬件
        /// </summary>
        /// <returns></returns>
        public async Task<InitResult> InitAsync()
        {
            var cameraTask = Task.Run(() => Camera.Initialize(_settingProvider));
            var detectorTask = Task.Run(() => Detector.Initialize(_settingProvider));

            var listTaskResult = await Task.WhenAll(cameraTask, detectorTask);
            var listAllOK = listTaskResult.All(d => d);
            if (listAllOK)
            {
                Initialized = true;
                return new InitResult() { Success = true, Message = "所有硬件初始化成功！" };
            }

            var sb = new StringBuilder("硬件初始化失败：");
            if (!cameraTask.Result) sb.Append("相机丨");
            if (!detectorTask.Result) sb.Append("平板探测器丨");
            sb = sb.Remove(sb.Length - 1, 1);
            return new InitResult() { Success = false, Message = sb.ToString() };
        }

        /// <summary>
        /// 关闭所有硬件
        /// </summary>
        /// <returns></returns>
        public void Close()
        {
            try
            {
                Camera.Close();
            }
            catch (Exception ex)
            {
                Logs.LogError(ex);
            }

            try
            {
                Detector.Close();
            }
            catch (Exception ex)
            {
                Logs.LogError(ex);
            }
        }
    }
}
